<template>
  <div class="team-contract-container">
    <!-- 筛选条件 -->
    <el-card class="filter-card" shadow="never">
      <el-form :model="filterForm" :inline="true" label-width="80px">
        <el-form-item label="合同编号">
          <el-input
            v-model="filterForm.contractNo"
            placeholder="请输入合同编号"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        
        <el-form-item label="客户姓名">
          <el-input
            v-model="filterForm.customerName"
            placeholder="请输入客户姓名"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        
        <el-form-item label="签约时间">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        
        <el-form-item label="合同状态">
          <el-select v-model="filterForm.status" placeholder="请选择合同状态" clearable>
            <el-option label="全部" value="" />
            <el-option label="草稿" value="draft" />
            <el-option label="待审核" value="pending" />
            <el-option label="已生效" value="active" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="业务员">
          <el-select
            v-model="filterForm.salesmanId"
            placeholder="请选择业务员"
            clearable
            filterable
          >
            <el-option label="全部" value="" />
            <el-option
              v-for="salesman in salesmanList"
              :key="salesman.id"
              :label="salesman.name"
              :value="salesman.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleFilter" :loading="loading">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计概览 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="4">
        <el-card class="stats-card">
          <div class="stats-item">
            <div class="stats-icon total">
              <el-icon><Document /></el-icon>
            </div>
            <div class="stats-content">
              <div class="stats-value">{{ statsData.totalContracts }}</div>
              <div class="stats-label">总合同数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="4">
        <el-card class="stats-card">
          <div class="stats-item">
            <div class="stats-icon active">
              <el-icon><CircleCheck /></el-icon>
            </div>
            <div class="stats-content">
              <div class="stats-value">{{ statsData.activeContracts }}</div>
              <div class="stats-label">生效合同</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="4">
        <el-card class="stats-card">
          <div class="stats-item">
            <div class="stats-icon amount">
              <el-icon><Money /></el-icon>
            </div>
            <div class="stats-content">
              <div class="stats-value">{{ formatNumber(statsData.totalAmount) }}</div>
              <div class="stats-label">合同总额(万元)</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="4">
        <el-card class="stats-card">
          <div class="stats-item">
            <div class="stats-icon month">
              <el-icon><TrendCharts /></el-icon>
            </div>
            <div class="stats-content">
              <div class="stats-value">{{ statsData.monthContracts }}</div>
              <div class="stats-label">本月新增</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="4">
        <el-card class="stats-card">
          <div class="stats-item">
            <div class="stats-icon pending">
              <el-icon><Clock /></el-icon>
            </div>
            <div class="stats-content">
              <div class="stats-value">{{ statsData.pendingContracts }}</div>
              <div class="stats-label">待审核</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="4">
        <el-card class="stats-card">
          <div class="stats-item">
            <div class="stats-icon rate">
              <el-icon><DataAnalysis /></el-icon>
            </div>
            <div class="stats-content">
              <div class="stats-value">{{ (statsData.completionRate * 100).toFixed(1) }}%</div>
              <div class="stats-label">完成率</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 合同表格 -->
    <el-card class="table-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span>团队合同列表</span>
          <div class="header-actions">
            <el-button type="primary" size="small" @click="handleAdd">
              <el-icon><Plus /></el-icon>
              新增合同
            </el-button>
            <el-button type="success" size="small" @click="handleExport">
              <el-icon><Download /></el-icon>
              导出合同
            </el-button>
            <el-button type="warning" size="small" @click="handleBatchApprove" :disabled="selectedRows.length === 0">
              <el-icon><Check /></el-icon>
              批量审核
            </el-button>
          </div>
        </div>
      </template>
      
      <el-table
        v-loading="loading"
        :data="tableData"
        stripe
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="contractNo" label="合同编号" width="150" />
        <el-table-column prop="customerName" label="客户姓名" width="120" />
        <el-table-column prop="customerPhone" label="客户电话" width="130" />
        <el-table-column prop="propertyInfo" label="房产信息" width="200" show-overflow-tooltip />
        <el-table-column prop="contractAmount" label="合同金额(万元)" width="140" align="right">
          <template #default="{ row }">
            <span class="amount-text">{{ formatNumber(row.contractAmount) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="commission" label="佣金(万元)" width="120" align="right">
          <template #default="{ row }">
            <span class="commission-text">{{ formatNumber(row.commission) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="salesmanName" label="业务员" width="100" />
        <el-table-column prop="signDate" label="签约日期" width="120" />
        <el-table-column prop="status" label="合同状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTag(row.status)">
              {{ getStatusName(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="progress" label="执行进度" width="120">
          <template #default="{ row }">
            <el-progress
              :percentage="row.progress"
              :color="getProgressColor(row.progress)"
              :stroke-width="8"
              text-inside
            />
          </template>
        </el-table-column>
        <el-table-column prop="nextPayDate" label="下次付款" width="120" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleView(row)">
              查看
            </el-button>
            <el-button type="success" size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-dropdown @command="(command) => handleMoreAction(command, row)">
              <el-button type="info" size="small">
                更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="approve" v-if="row.status === 'pending'">审核</el-dropdown-item>
                  <el-dropdown-item command="print">打印</el-dropdown-item>
                  <el-dropdown-item command="copy">复制</el-dropdown-item>
                  <el-dropdown-item command="cancel" v-if="row.status !== 'cancelled'">取消</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 合同详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="合同详情"
      width="80%"
      @close="handleDetailDialogClose"
    >
      <div v-if="currentContract" class="contract-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="合同编号">{{ currentContract.contractNo }}</el-descriptions-item>
          <el-descriptions-item label="客户姓名">{{ currentContract.customerName }}</el-descriptions-item>
          <el-descriptions-item label="客户电话">{{ currentContract.customerPhone }}</el-descriptions-item>
          <el-descriptions-item label="房产信息">{{ currentContract.propertyInfo }}</el-descriptions-item>
          <el-descriptions-item label="合同金额">{{ formatNumber(currentContract.contractAmount) }}万元</el-descriptions-item>
          <el-descriptions-item label="佣金">{{ formatNumber(currentContract.commission) }}万元</el-descriptions-item>
          <el-descriptions-item label="业务员">{{ currentContract.salesmanName }}</el-descriptions-item>
          <el-descriptions-item label="签约日期">{{ currentContract.signDate }}</el-descriptions-item>
          <el-descriptions-item label="合同状态">
            <el-tag :type="getStatusTag(currentContract.status)">
              {{ getStatusName(currentContract.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="执行进度">
            <el-progress
              :percentage="currentContract.progress"
              :color="getProgressColor(currentContract.progress)"
            />
          </el-descriptions-item>
        </el-descriptions>
        
        <div class="contract-attachments" v-if="currentContract.attachments">
          <h4>合同附件</h4>
          <el-upload
            :file-list="currentContract.attachments"
            :show-file-list="true"
            :auto-upload="false"
            list-type="text"
          >
          </el-upload>
        </div>
      </div>
      
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="handlePrint">打印合同</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Search, 
  Refresh, 
  Plus, 
  Download, 
  Check, 
  Document, 
  CircleCheck, 
  Money, 
  TrendCharts, 
  Clock, 
  DataAnalysis,
  ArrowDown
} from '@element-plus/icons-vue'

// 响应式数据
const loading = ref(false)
const detailDialogVisible = ref(false)

// 筛选表单
const filterForm = reactive({
  contractNo: '',
  customerName: '',
  dateRange: [],
  status: '',
  salesmanId: ''
})

// 分页数据
const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

// 统计数据
const statsData = reactive({
  totalContracts: 0,
  activeContracts: 0,
  totalAmount: 0,
  monthContracts: 0,
  pendingContracts: 0,
  completionRate: 0
})

// 表格数据
const tableData = ref([])
const selectedRows = ref([])
const currentContract = ref(null)

// 下拉选项
const salesmanList = ref([])

// 方法
const handleFilter = () => {
  pagination.page = 1
  getTableData()
}

const handleReset = () => {
  Object.assign(filterForm, {
    contractNo: '',
    customerName: '',
    dateRange: [],
    status: '',
    salesmanId: ''
  })
  handleFilter()
}

const handleAdd = () => {
  ElMessage.info('新增合同功能开发中')
}

const handleExport = () => {
  ElMessage.success('导出功能开发中')
}

const handleBatchApprove = () => {
  ElMessage.info('批量审核功能开发中')
}

const handleView = (row: any) => {
  currentContract.value = row
  detailDialogVisible.value = true
}

const handleEdit = (row: any) => {
  ElMessage.info(`编辑合同 ${row.contractNo}`)
}

const handleMoreAction = (command: string, row: any) => {
  switch (command) {
    case 'approve':
      ElMessage.info(`审核合同 ${row.contractNo}`)
      break
    case 'print':
      ElMessage.info(`打印合同 ${row.contractNo}`)
      break
    case 'copy':
      ElMessage.info(`复制合同 ${row.contractNo}`)
      break
    case 'cancel':
      ElMessageBox.confirm(
        `确定要取消合同 ${row.contractNo} 吗？`,
        '确认取消',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        ElMessage.success('合同已取消')
        getTableData()
      })
      break
  }
}

const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection
}

const handleSizeChange = (size: number) => {
  pagination.size = size
  getTableData()
}

const handleCurrentChange = (page: number) => {
  pagination.page = page
  getTableData()
}

const handleDetailDialogClose = () => {
  currentContract.value = null
}

const handlePrint = () => {
  ElMessage.info('打印功能开发中')
}

const getTableData = async () => {
  loading.value = true
  try {
    // TODO: 调用API获取数据
    setTimeout(() => {
      tableData.value = [
        {
          contractNo: 'HT202401001',
          customerName: '张三',
          customerPhone: '13800138001',
          propertyInfo: '朝阳区某小区3室2厅',
          contractAmount: 350.5,
          commission: 10.5,
          salesmanName: '李四',
          signDate: '2024-01-15',
          status: 'active',
          progress: 75,
          nextPayDate: '2024-02-15',
          attachments: [
            { name: '购房合同.pdf', url: '/files/contract1.pdf' },
            { name: '身份证复印件.jpg', url: '/files/id1.jpg' }
          ]
        },
        {
          contractNo: 'HT202401002',
          customerName: '王五',
          customerPhone: '13800138002',
          propertyInfo: '海淀区某公寓2室1厅',
          contractAmount: 280.0,
          commission: 8.4,
          salesmanName: '赵六',
          signDate: '2024-01-14',
          status: 'pending',
          progress: 25,
          nextPayDate: '2024-01-20',
          attachments: []
        }
      ]
      pagination.total = 120
      
      // 更新统计数据
      Object.assign(statsData, {
        totalContracts: 120,
        activeContracts: 85,
        totalAmount: 2850.6,
        monthContracts: 25,
        pendingContracts: 15,
        completionRate: 0.78
      })
      
      loading.value = false
    }, 1000)
  } catch (error) {
    loading.value = false
    ElMessage.error('获取数据失败')
  }
}

// 工具方法
const formatNumber = (num: number) => {
  return num?.toFixed(2) || '0.00'
}

const getStatusTag = (status: string) => {
  const tagMap: Record<string, string> = {
    draft: 'info',
    pending: 'warning',
    active: 'success',
    completed: 'primary',
    cancelled: 'danger'
  }
  return tagMap[status] || 'info'
}

const getStatusName = (status: string) => {
  const nameMap: Record<string, string> = {
    draft: '草稿',
    pending: '待审核',
    active: '已生效',
    completed: '已完成',
    cancelled: '已取消'
  }
  return nameMap[status] || status
}

const getProgressColor = (progress: number) => {
  if (progress >= 80) return '#67c23a'
  if (progress >= 60) return '#e6a23c'
  if (progress >= 40) return '#f56c6c'
  return '#909399'
}

// 初始化数据
const initData = () => {
  salesmanList.value = [
    { id: '1', name: '李四' },
    { id: '2', name: '赵六' },
    { id: '3', name: '孙七' }
  ]
  
  getTableData()
}

onMounted(() => {
  initData()
})
</script>

<style lang="scss" scoped>
.team-contract-container {
  padding: 20px;
  
  .filter-card {
    margin-bottom: 20px;
  }
  
  .stats-row {
    margin-bottom: 20px;
    
    .stats-card {
      .stats-item {
        display: flex;
        align-items: center;
        
        .stats-icon {
          width: 50px;
          height: 50px;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 12px;
          font-size: 20px;
          color: white;
          
          &.total {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
          }
          
          &.active {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
          }
          
          &.amount {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
          }
          
          &.month {
            background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
          }
          
          &.pending {
            background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
          }
          
          &.rate {
            background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);
          }
        }
        
        .stats-content {
          .stats-value {
            font-size: 20px;
            font-weight: bold;
            color: #303133;
            margin-bottom: 3px;
          }
          
          .stats-label {
            font-size: 12px;
            color: #909399;
          }
        }
      }
    }
  }
  
  .table-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .header-actions {
        display: flex;
        gap: 10px;
      }
    }
    
    .amount-text {
      color: #67c23a;
      font-weight: bold;
    }
    
    .commission-text {
      color: #e6a23c;
      font-weight: bold;
    }
    
    .pagination-container {
      margin-top: 20px;
      text-align: right;
    }
  }
  
  .contract-detail {
    .contract-attachments {
      margin-top: 20px;
      
      h4 {
        margin-bottom: 10px;
        color: #303133;
      }
    }
  }
}
</style>
